package Teacher_Test.JDBC_test.utils;

import org.apache.commons.dbcp.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DBPoollUtils {
//    数据源对象
    public static DataSource datasource= null;

    public static ThreadLocal<Connection> threadLocal= new ThreadLocal<Connection>();

    static {
        Properties properties=new Properties();
        try {
            properties.load(DBPoollUtils.class.getClassLoader().getResourceAsStream("db.properties"));
            datasource= BasicDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection(){

        Connection connection= threadLocal.get();

        if (connection == null){
            try {
                connection=datasource.getConnection();
                threadLocal.set(connection);
                return connection;
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return connection;
    }

}
